﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.IO;
using System.Data.SqlClient;
using System.Xml;
using ZEBuz.Questionnaire.Lib.Util;
using ZEBuz.Questionnaire.Lib.Entities;
using System.Web;
using Microsoft.ApplicationBlocks.Data;
using System.Web.Caching;

namespace ZEBuz.Questionnaire.Lib.Entities
{
    public partial class Questionnaire
    {
        private static readonly string CONST_PREFIX_QUESTIONNAIRE = "questionnaire_";
        public int Id { get; set; }
        public XMLQuestionnaire QuestionnaireDTO { get; set; }

        public Questionnaire() { }
        public Questionnaire(int id)
        {
            //todo: 做成全部包进去的功能
        }

        public Questionnaire GetFromCache(int id)
        {
            Questionnaire qn = System.Web.HttpContext.Current.Cache.Get(CONST_PREFIX_QUESTIONNAIRE + id) as Questionnaire;
            return qn;
        }

        public void AddToCache(Questionnaire qn)
        {
            System.Web.HttpContext.Current.Cache.Add(CONST_PREFIX_QUESTIONNAIRE + qn.Id, qn,
                null,
                Cache.NoAbsoluteExpiration, Cache.NoSlidingExpiration,
                System.Web.Caching.CacheItemPriority.High,
                null);
        }

        public Questionnaire Get(int id)
        {
            Questionnaire qn = GetFromCache(id);
            if (qn == null)
            {
                qn = new Questionnaire { Id = id, QuestionnaireDTO = XMLQuestionnaire.GetEntityFromXML("OLSON") };
                AddToCache(qn);
            }
            return qn;
        }

        private string GetPath(int questionnaireID)
        {
            string path = string.Empty;

            using (SqlConnection conn = new SqlConnection(Const.ConnectionString))
            {
                if (conn.State != System.Data.ConnectionState.Open)
                    conn.Open();

                SqlCommand comm = new SqlCommand(
                    "SELECT * FROM QUESTIONNARE WHERE QUESTIONNAIREID=" + questionnaireID,
                    conn);
                SqlDataReader dr = comm.ExecuteReader();
                if (dr.Read())
                {
                    path = dr["path"].ToString();
                }
                dr.Dispose();
            }

            return path;
        }

    }
}
